package com.dx.mes.service.tool.service;

import com.dx.common.table.ppt.*;
import com.dx.mes.common.core.his.HistoryManager;
import com.dx.mes.common.dao.*;
import com.dx.mes.common.table.rtnBean.SimpleRtnBeen;
import com.dx.mes.common.transcoder.util.AppContext;
import com.dx.mes.common.transcoder.util.JacksonUtil;
import com.dx.mes.common.transcoder.util.LogUtils;
import com.dx.mes.common.transcoder.util.Util;
import com.dx.mes.facade.tool.service.IFtptolopeService;
import com.dx.mes.facade.tool.tx.Ftptolope.FtptolopeI;
import com.dx.mes.facade.tool.tx.Ftptolope.FtptolopeIA;
import com.dx.mes.facade.tool.tx.Ftptolope.FtptolopeIB;
import com.dx.mes.facade.tool.tx.Ftptolope.FtptolopeO;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import static com.dx.mes.common.bean.def.GenericDef.*;


@Service("ftptolopeService")
public class FtptolopeService implements IFtptolopeService{
	private LogUtils logUtils;
	private static String TX_NAME = T_FTPTOLOPE;

	@Autowired
	private IBisToolDao bisToolDao;
	@Autowired
	private IRetToolStDao retToolStDao;
	@Autowired
	private IRetToolPtDao retToolPtDao;
	@Autowired
	private IRetToolStRlnDao retToolStRlnDao;
	@Autowired
	private IBisDataDao bisDataDao;
	@Autowired
	private IRetToolPmDao retToolPmDao;
	@Autowired
	private IRetToolInfoDao retToolInfoDao;
	@Resource
	private HistoryManager historyManager;

	private String sendhis_flag = "";
	@Override
	public String subMainProc(String evt_no, String strInMsg) {
		AppContext.clear();
		AppContext.setCurrServiceName(FtptolopeService.class.getSimpleName());
		AppContext.setCurrEventNumber(evt_no);
		logUtils = new LogUtils(FtptolopeService.class);
//		logUtils.info("[InTrx:" + strInMsg + "]");

		Session session = bisToolDao.getCrSession();
		long rtnCode = _NORMAL;
		String outMsg = null;

		FtptolopeI inTrx = new FtptolopeI();
		FtptolopeO outTrx = new FtptolopeO();
		outTrx.setTrx_id(TX_NAME);
		outTrx.setRtn_code(String.valueOf(RETURN_CODE_SET_ERROR));
		outTrx.setType_id(TRX_OUT);


		try {
			inTrx = JacksonUtil.fromJson(strInMsg, FtptolopeI.class);
			rtnCode = subMainProc2(inTrx, outTrx);
			if (rtnCode != _NORMAL) {
				TransactionAspectSupport.currentTransactionStatus()
						.setRollbackOnly();
				outTrx.setRtn_code(String.valueOf(rtnCode));
			} else {
				if (!Util.isSpaceCheck(sendhis_flag) && historyManager.isTransactionSuccessed(sendhis_flag)) {
					historyManager.sendHistoryMessageToRabbitMQ(evt_no);
				}
				outTrx.setRtn_code(String.valueOf(RETURN_CODE_OK));
				outTrx.setRtn_mesg(RETURN_MESG_OK);
				session.flush();

			}
		} catch (Exception ex) {
			TransactionAspectSupport.currentTransactionStatus()
					.setRollbackOnly();
			outTrx.setRtn_mesg(ex.toString());
			outTrx.setRtn_code(RETURN_CODE_UNKNOWN);
//			logUtils.error(Util.stackTraceToString(ex));
		} finally {
			outMsg = JacksonUtil.toJSONStr(outTrx);
//			logUtils.info("[OutTrx:" + outMsg + "]");
		}
		return outMsg;
	}

	private long subMainProc2(FtptolopeI inTrx, FtptolopeO outTrx) {
		long lRc = _NORMAL;
		char actionType = inTrx.getAction_flg().toCharArray()[0];
		Timestamp gEvtTimestamp = Util.getCurrentTimestamp();
		switch (actionType) {
			case 'A': {
				lRc = updTolStat(inTrx, outTrx, gEvtTimestamp);
				if (lRc != _NORMAL) {
					return lRc;
				}
				break;
			}
			case 'B':{
				lRc = updPorStat(inTrx, outTrx,gEvtTimestamp);
				if (lRc != _NORMAL) {
					return lRc;
				}
				break;
			}
			case 'C':{
				lRc = updLockFlg(inTrx, outTrx,gEvtTimestamp);
				if (lRc != _NORMAL) {
					return lRc;
				}
				break;
			}
			case 'D':{
				lRc = updLockFlg(inTrx, outTrx,gEvtTimestamp);
				if (lRc != _NORMAL) {
					return lRc;
				}
				break;
			}
			case 'E':{
				lRc = updHoldFlg(inTrx,outTrx,gEvtTimestamp);
				if (lRc != _NORMAL) {
					return lRc;
				}
				break;
			}
			case 'F':{
				lRc = updHoldFlg(inTrx,outTrx,gEvtTimestamp);
				if (lRc != _NORMAL) {
					return lRc;
				}
				break;
			}
			case 'G':{
				lRc = updNote(inTrx,outTrx,gEvtTimestamp);
				if (lRc != _NORMAL) {
					return lRc;
				}
				break;
			}
			case 'H':{
				lRc = updRunMode(inTrx,outTrx,gEvtTimestamp);
				if (lRc != _NORMAL) {
					return lRc;
				}
				break;
			}
			default: {
				outTrx.setRtn_mesg("Invalide type input: [" + actionType + "]");
				return E_FTPTOLOPE_INVALID_INPUT;
			}
		}
		return lRc;
	}

	private long updRunMode(FtptolopeI inTrx, FtptolopeO outTrx, Timestamp gEvtTimestamp) {
		long lRc = _NORMAL;
		String gszMsgBuf = "";
		FtptolopeIA iary = inTrx.getIary().get(0);
		Ret_tool_st ret_tool_st = retToolStDao.get(iary.getTool_id());
		if (null == ret_tool_st) {
			gszMsgBuf = "设备号为 [" + iary.getTool_id() + "]的机台不存在，不允许操作!";
			outTrx.setRtn_mesg(gszMsgBuf);
			return E_FTPTOLOPE_INVALID_TOOL_STAT;
		}
		Bis_tool bis_tool = bisToolDao.get(iary.getTool_id());
		if(!bis_tool.getUnit_typ().equals(TOOL_UNIT_MAIN)){
			gszMsgBuf = "设备号为 [" + iary.getTool_id() + "]的机台不是主设备，无需更改设备运行模式!";
			outTrx.setRtn_mesg(gszMsgBuf);
			return E_FTPTOLOPE_INVALID_TOOL_UNIT_TYPE;
		}
		ret_tool_st.setTool_run_mode(iary.getTool_run_mode());
		ret_tool_st.setEvt_usr(inTrx.getEvt_user());
		ret_tool_st.setEvt_timestamp(gEvtTimestamp);
		retToolStDao.saveOrUpdate(ret_tool_st);

		return lRc;
	}

	private long updNote(FtptolopeI inTrx, FtptolopeO outTrx, Timestamp gEvtTimestamp) {
		long lRc = _NORMAL;
		String gszMsgBuf = "";
		FtptolopeIA iary = inTrx.getIary().get(0);
		Ret_tool_st ret_tool_st = retToolStDao.get(iary.getTool_id());
		if (null == ret_tool_st) {
			gszMsgBuf = "设备号为 [" + iary.getTool_id() + "]的机台不存在，不允许操作!";
			outTrx.setRtn_mesg(gszMsgBuf);
			return E_FTPTOLOPE_INVALID_TOOL_STAT;
		}
		ret_tool_st.setTool_note(iary.getTool_note());
		ret_tool_st.setEvt_usr(inTrx.getEvt_user());
		ret_tool_st.setEvt_timestamp(gEvtTimestamp);
		retToolStDao.saveOrUpdate(ret_tool_st);

		return lRc;
	}

	private long updHoldFlg(FtptolopeI inTrx, FtptolopeO outTrx, Timestamp gEvtTimestamp) {
		long lRc = _NORMAL;
		String gszMsgBuf = "";
		FtptolopeIA iary = inTrx.getIary().get(0);
		Ret_tool_st ret_tool_st = retToolStDao.get(iary.getTool_id());
		if (null == ret_tool_st) {
			gszMsgBuf = "设备号为 [" + iary.getTool_id() + "]的机台不存在，不允许操作!";
			outTrx.setRtn_mesg(gszMsgBuf);
			return E_FTPTOLOPE_INVALID_TOOL_STAT;
		}
		if(_YES.equals(iary.getTool_hold_flg())&&_YES.equals(ret_tool_st.getTool_hold_flg())){
			gszMsgBuf = "设备号为 [" + iary.getTool_id() + "]的设备已经HOLD，无须重复操作!";
			outTrx.setRtn_mesg(gszMsgBuf);
			return E_FTPTOLOPE_INVALID_TOOL_STAT;
		}
		if(_NO.equals(iary.getTool_hold_flg())&&_NO.equals(ret_tool_st.getTool_hold_flg())){
			gszMsgBuf = "设备号为 [" + iary.getTool_id() + "]的设备已经解HOLD，无须重复操作!";
			outTrx.setRtn_mesg(gszMsgBuf);
			return E_FTPTOLOPE_INVALID_TOOL_STAT;
		}
		ret_tool_st.setTool_hold_flg(iary.getTool_hold_flg());
		ret_tool_st.setEvt_usr(inTrx.getEvt_user());
		ret_tool_st.setEvt_timestamp(gEvtTimestamp);
		ret_tool_st.setPv_clm_timestamp(ret_tool_st.getClm_timestamp());
		ret_tool_st.setClm_timestamp(gEvtTimestamp);
		retToolStDao.saveOrUpdate(ret_tool_st);

		return lRc;
	}

	private long updLockFlg(FtptolopeI inTrx, FtptolopeO outTrx, Timestamp gEvtTimestamp) {
		long lRc = _NORMAL;
		String gszMsgBuf = "";
		FtptolopeIA iary = inTrx.getIary().get(0);

		Ret_tool_st ret_tool_st = retToolStDao.get(iary.getTool_id());
		if (null == ret_tool_st) {
			gszMsgBuf = "设备号为 [" + iary.getTool_id() + "]的设备不存在，不允许操作!";
			outTrx.setRtn_mesg(gszMsgBuf);
			return E_FTPTOLOPE_INVALID_TOOL_STAT;
		}
		if(_YES.equals(iary.getTool_lock_flg())&&_YES.equals(ret_tool_st.getTool_lock_flg())){
			gszMsgBuf = "设备号为 [" + iary.getTool_id() + "]的设备已经锁定，无须重复操作!";
			outTrx.setRtn_mesg(gszMsgBuf);
			return E_FTPTOLOPE_INVALID_TOOL_STAT;
		}
		if(_NO.equals(iary.getTool_lock_flg())&&_NO.equals(ret_tool_st.getTool_lock_flg())){
			gszMsgBuf = "设备号为 [" + iary.getTool_id() + "]的设备已经解锁，无须重复操作!";
			outTrx.setRtn_mesg(gszMsgBuf);
			return E_FTPTOLOPE_INVALID_TOOL_STAT;
		}
		ret_tool_st.setTool_lock_flg(iary.getTool_lock_flg());
		ret_tool_st.setEvt_usr(inTrx.getEvt_user());
		ret_tool_st.setPv_clm_timestamp(ret_tool_st.getClm_timestamp());
		ret_tool_st.setClm_timestamp(gEvtTimestamp);
		ret_tool_st.setEvt_timestamp(gEvtTimestamp);
		retToolStDao.saveOrUpdate(ret_tool_st);

		return lRc;
	}

	private long updPorStat(FtptolopeI inTrx, FtptolopeO outTrx, Timestamp gEvtTimestamp) {
		long lRc = _NORMAL;
		String gszMsgBuf = "";
		FtptolopeIB iaryB = inTrx.getIaryB().get(0);
		Ret_tool_ptId ptId = new Ret_tool_ptId(iaryB.getTool_id_fk(), iaryB.getPort_id());
		Ret_tool_pt ret_tool_pt = retToolPtDao.get(ptId);
		if (null == ret_tool_pt) {
			gszMsgBuf = "设备代码为 [" + iaryB.getTool_id_fk() + "]的端口号["+iaryB.getPort_id()+"]不存在，不允许操作!";
			outTrx.setRtn_mesg(gszMsgBuf);
			return E_FTPTOLOPE_INVALID_TOOL_STAT;
		}
		Ret_tool_st ret_tool_st = retToolStDao.get(iaryB.getTool_id_fk());
		if (ret_tool_st.getTool_lock_flg().equals("Y")) {
			gszMsgBuf = "设备号为 [" + iaryB.getTool_id_fk() + "]的机台被锁定，不允许更改状态!";
			outTrx.setRtn_mesg(gszMsgBuf);
			return E_FTPTOLOPE_INVALID_TOOL_LOCK;
		}
		ret_tool_pt.setPort_stat(iaryB.getPort_stat());
		ret_tool_pt.setEvt_usr(inTrx.getEvt_user());
		ret_tool_pt.setEvt_timestamp(gEvtTimestamp);
		retToolPtDao.update(ret_tool_pt);
		return lRc;
	}

	private long updTolStat(FtptolopeI inTrx, FtptolopeO outTrx, Timestamp gEvtTimestamp) {
		long toolstartTime = System.currentTimeMillis();
		long lRc = _NORMAL;
		String gszMsgBuf = "";
		if (!StringUtils.isEmpty(inTrx.getClm_timestamp())) {
			gEvtTimestamp = Timestamp.valueOf(inTrx.getClm_timestamp());
		}
		//信号灯特殊处理
		if ("Y".equals(inTrx.getSignal_lamp()) && StringUtils.isEmpty(inTrx.getStart_up_flg())) {
			String serial = inTrx.getHd_serial_num();
//            ArrayList<String> serialList= new ArrayList<String>(){{add("0127");
//				add("0150");
//				add("0042");
//				add("0110");
//				add("0139");
//				add("0089");
//				add("0005");
//				add("0071");
//				add("0090");
//				add("0099");
//				add("0073");
//				add("0083");
//				add("0086");
//				add("0069");
//				add("0128");
//				add("0076");
//				add("0108");
//				add("0075");
//				add("0032");
//				add("0064");
//				add("0112");
//				add("0004");
//				add("0077");
//				add("0011");
//				add("0142");
//			}};
//            if(!serialList.contains(serial)){
//				return 3333333;
//			}
			String channnel_state = inTrx.getChannnel_state();
			SimpleRtnBeen rtnBeen = signalLamp(serial, channnel_state);
			if (rtnBeen.getlRc() != 0000000) {
				gszMsgBuf = rtnBeen.getMsgBuf();
				outTrx.setRtn_mesg(gszMsgBuf);
				return E_FTPTOLOPE_INVALID_TOOL_STAT;
			}

			String toolStatus = rtnBeen.getMsgBuf();
			String[] toolStatusArr = toolStatus.split("_");
			String toolId = toolStatusArr[0];
			String toolstatus = toolStatusArr[1];

			if (!StringUtils.isEmpty(toolstatus)) {
				Ret_tool_st ret_tool_st = retToolStDao.get(toolId);
				if (null == ret_tool_st) {
					gszMsgBuf = "设备号为 [" + toolId + "]的机台不存在，不允许操作!";
					outTrx.setRtn_mesg(gszMsgBuf);
					return E_FTPTOLOPE_INVALID_TOOL_STAT;
				}
				if (ret_tool_st.getTool_lock_flg().equals("Y")) {
					gszMsgBuf = "设备号为 [" + toolId + "]的机台被锁定，不允许更改状态!";
					outTrx.setRtn_mesg(gszMsgBuf);
					return E_FTPTOLOPE_INVALID_TOOL_LOCK;
				}
				//判断当前状态和传入的状态是否一样
				if (!ret_tool_st.getTool_stat().equals(toolstatus)) {
					ret_tool_st.setPv_tool_stat(ret_tool_st.getTool_stat());
					ret_tool_st.setPv_tool_sub_stat(ret_tool_st.getTool_sub_stat());
					ret_tool_st.setTool_stat(toolstatus);
					String hql = "From Bis_data where data_cate = 'EQST' and data_id = '" + toolstatus + "'";
					List<Bis_data> list = bisDataDao.find(hql);
					if (list != null && list.size() > 0) {
						ret_tool_st.setTool_sub_stat(list.get(0).getData_ext());
					}
					ret_tool_st.setPv_clm_timestamp(ret_tool_st.getClm_timestamp());
					ret_tool_st.setClm_timestamp(gEvtTimestamp);
//                ret_tool_st.setRsn_code(iary.getRsn_code());
//                ret_tool_st.setRsn_code_dsc(iary.getRsn_code_dsc());
					ret_tool_st.setEvt_usr(inTrx.getEvt_user());
					ret_tool_st.setEvt_timestamp(gEvtTimestamp);
					retToolStDao.saveOrUpdate(ret_tool_st);
				}
			} else {
				gszMsgBuf = "信号灯设备状态为空！请确认bis_data设置";
				outTrx.setRtn_mesg(gszMsgBuf);
				return E_FTPTOLOPE_INVALID_TOOL_STAT;
			}
			sendhis_flag = "0000000";
			return lRc;
		}

		//pecvd的特殊处理
		if (inTrx.getSpeciall_type() != null && "pecvd".equals(inTrx.getSpeciall_type())) {
			lRc = dealToolStat(inTrx, outTrx, gEvtTimestamp);
			return lRc;
		} else {
			FtptolopeIA iary = inTrx.getIary().get(0);
			Ret_tool_st ret_tool_st = retToolStDao.get(iary.getTool_id());
			if (null == ret_tool_st) {
				gszMsgBuf = "设备号为 [" + iary.getTool_id() + "]的机台不存在，不允许操作!";
				outTrx.setRtn_mesg(gszMsgBuf);
				return E_FTPTOLOPE_INVALID_TOOL_STAT;
			}
			if (ret_tool_st.getTool_lock_flg().equals("Y")) {
				gszMsgBuf = "设备号为 [" + iary.getTool_id() + "]的机台被锁定，不允许更改状态!";
				outTrx.setRtn_mesg(gszMsgBuf);
				return E_FTPTOLOPE_INVALID_TOOL_LOCK;
			}
			if (StringUtils.isEmpty(iary.getTool_stat())) {
				gszMsgBuf = "设备号为 [" + iary.getTool_id() + "]的输入状态为空!";
				outTrx.setRtn_mesg(gszMsgBuf);
				return E_FTPTOLOPE_INVALID_TOOL_STAT;
			}

			if (!ret_tool_st.getTool_stat().equals(iary.getTool_stat())) {
				ret_tool_st.setPv_tool_stat(ret_tool_st.getTool_stat());
				ret_tool_st.setPv_tool_sub_stat(ret_tool_st.getTool_sub_stat());
				String hql = "From Bis_data where data_cate = 'EQST' and data_id = '" + iary.getTool_stat().trim() + "'";
				List<Bis_data> list = bisDataDao.find(hql);
				if (list.size() > 0) {//机台上报的
					ret_tool_st.setTool_stat(iary.getTool_stat());
					ret_tool_st.setTool_sub_stat(list.get(0).getData_ext());
				} else {//mes前端传的值
					String sql = "From Bis_data where data_cate = 'EQST' and data_ext = '" + iary.getTool_stat().trim() + "'";
					List<Bis_data> listA = bisDataDao.find(sql);
					if (listA.size() > 0) {
						ret_tool_st.setTool_stat(listA.get(0).getData_id());
						ret_tool_st.setTool_sub_stat(iary.getTool_stat());
					} else {
						return E_FTPTOLOPE_INVALID_TOOL_STAT;
					}
				}

				ret_tool_st.setPv_clm_timestamp(ret_tool_st.getClm_timestamp());
				ret_tool_st.setClm_timestamp(gEvtTimestamp);
				ret_tool_st.setRsn_code(iary.getRsn_code());
				ret_tool_st.setRsn_code_dsc(iary.getRsn_code_dsc());
				ret_tool_st.setEvt_usr(inTrx.getEvt_user());
				ret_tool_st.setEvt_timestamp(gEvtTimestamp);
				retToolStDao.saveOrUpdate(ret_tool_st);

				//保养
				Ret_tool_st ret_tool_stM = retToolStDao.get(iary.getTool_id());
				if (_PM.equals(ret_tool_stM.getTool_stat()) && !_NO.equals(inTrx.getOpi_ope_flg())) {//如果是切换为pm状态，则需要开启保养
					Ret_tool_pm ret_tool_pm = retToolPmDao.get(iary.getPm_evt_seq_id());
					// 系统当前时间
					Timestamp NowDate = Util.getCurrentTimestamp();
					//保养开始时间
					Timestamp StratDate = new Timestamp(ret_tool_pm.getFrom_date().getTime());
					Timestamp EndDate = new Timestamp(ret_tool_pm.getTo_date().getTime());
					if (NowDate.before(StratDate)) {
						gszMsgBuf = "保养计划不能提前进行！";
						outTrx.setRtn_mesg(gszMsgBuf);
						return E_MTPTOOLPM_PM_TYP_NOT_EXIST;
					}
					if (EndDate.before(NowDate)) {
						gszMsgBuf = "该保养计划已过期！";
						outTrx.setRtn_mesg(gszMsgBuf);
						return E_MTPTOOLPM_PM_TYP_NOT_EXIST;
					}
					if (ret_tool_pm != null) {
						ret_tool_pm.setPm_stat(PROC_IN_PROCESS);
						ret_tool_pm.setAc_pm_beg_timestamp(Util.getCurrentTimestamp());
						retToolPmDao.saveOrUpdate(ret_tool_pm);
					} else {
						gszMsgBuf = "保养计划信息不存在!";
						outTrx.setRtn_mesg(gszMsgBuf);
						return E_MTPTOOLPM_PM_TYP_NOT_EXIST;
					}
				}
			}
			return lRc;
		}
	}

	public SimpleRtnBeen signalLamp(String serial, String channnel_state){
        SimpleRtnBeen simpleRtnBeen  = new SimpleRtnBeen();
        ArrayList<Integer> IntegerList = new ArrayList<Integer>(){{add(0); add(1);add(2);add(3);}};
        String hql = "From Bis_data where data_cate = 'TLSL'";
        hql += " and ext_2 = '" + serial +"'";
        List<Bis_data> bisDataList = bisDataDao.find(hql);
        if(bisDataList == null || bisDataList.size() == 0){
            return  new SimpleRtnBeen(9999999,"相关硬件序列号未找到对应设备！");
        }
        String toolId = bisDataList.get(0).getExt_1();
        //红R 》 黄Y 》 绿 G   1>3>2>0    0000：红 绿 黄 蓝  0灭，其他都代表亮
        String key = "0";//灭
        String str = channnel_state;

        int a = str.indexOf(key);//*第一个出现的索引位置
        ArrayList<Integer>  arrlist =  new ArrayList<Integer>();
        while (a != -1) {
//            System.out.print(a + "\t");
            arrlist.add(a);
            a = str.indexOf(key, a + 1);//*从这个索引往后开始第一个出现的位置
        }

        List<Bis_data> bisDataList1 = new ArrayList<>();
        for(int i = 0 ; i < IntegerList.size(); i++){
            if(arrlist.contains(IntegerList.get(i))){
                continue;
            }else{
                String hql2 = "From Bis_data where data_cate = 'SINC'";
                hql2 += " and ext_1 ='" + (IntegerList.get(i)+1) +"'";
                List<Bis_data> bis_dataList = bisDataDao.find(hql2);
                if(bis_dataList != null && bis_dataList.size() > 0){
                    bisDataList1.add(bis_dataList.get(0));
                }
            }
        }

        String status = "";
        if(bisDataList1 != null && bisDataList1.size() > 0){
            Collections.sort(bisDataList1,new Comparator<Bis_data>() {
                @Override
                public int compare(Bis_data bis_data1, Bis_data bis_data2) {
                    if(Integer.valueOf(bis_data1.getExt_4()) > Integer.valueOf(bis_data2.getExt_4())){
                        return 1;
                    }else if(Integer.valueOf(bis_data1.getExt_4()) < Integer.valueOf(bis_data2.getExt_4())){
                        return  -1;
                    }else {
                        return -1;
                    }
                }
            });
            status = bisDataList1.get(0).getExt_3();
        }else{
            return new SimpleRtnBeen(9999999,"信号灯不是开机状态，但为0000！");
        }

        simpleRtnBeen.setMsgBuf(toolId+"_"+status);
        simpleRtnBeen.setlRc(0000000);
        return  simpleRtnBeen;
    }

	//特殊处理pecvd状态
	public long  dealToolStat(FtptolopeI inTrx, FtptolopeO outTrx,Timestamp gEvtTimestamp){
		long lRc = _NORMAL;
		List<FtptolopeIA> iaryList = inTrx.getIary();
		FtptolopeIA iary = iaryList.get(0);
		String toolId = iary.getTool_id();
		String variableName = iary.getVariable_Name();
		String toolStat = iary.getTool_stat();
		String mainTool= toolId.split("_")[0];
		String position= toolId.split("_")[1];
		ArrayList<Integer> indexList = testStringIndexOf2(toolStat);
		String hql1 = "From Bis_data where data_cate = 'PECF' ";
		//[{"tool_id":"PE20_LIFT","variable_Name":"MW08","tool_stat":"111111"}]
		if("LIFT".equals(position)){//机械手
			hql1 += " and ext_1 ='机械手'";
		}else{//管体
			hql1 += " and ext_1 ='管体'";
		}
		hql1 += " and ext_2 ='" + variableName +"'";
		List<Bis_data> bisDataList = bisDataDao.find(hql1);
		if(bisDataList != null && bisDataList.size() > 0){
			List<Ret_tool_info> retToolInfoList = new ArrayList<>();
			for(Bis_data bis_data : bisDataList){
				if(StringUtils.isEmpty(bis_data.getExt_4())){
					continue;
				}else{
					Ret_tool_infoId retToolInfoId = new Ret_tool_infoId();
					retToolInfoId.setTool_id_fk(mainTool);
					retToolInfoId.setSub_tool_id_fk(toolId);
					retToolInfoId.setPoint_name(bis_data.getExt_4());
					Ret_tool_info retToolInfo = retToolInfoDao.get(retToolInfoId);
					if(retToolInfo == null){
						//不存在则新增
						Ret_tool_info newRetToolInfo = new Ret_tool_info();
						newRetToolInfo.setId(retToolInfoId);
						String bitIndex = bis_data.getExt_3();//唯一地址
						Integer bitIndexInteger = Integer.valueOf(bitIndex);
						if(indexList.contains(bitIndexInteger)){
							newRetToolInfo.setData_value("1");
						}else{
							newRetToolInfo.setData_value("0");
						}
						newRetToolInfo.setData_type("02");
						newRetToolInfo.setData_dsc(bis_data.getExt_5());
						newRetToolInfo.setEvt_usr(inTrx.getEvt_user());
						newRetToolInfo.setEvt_timestamp(gEvtTimestamp);
						retToolInfoList.add(newRetToolInfo);
					}else{
						//存在
						String bitIndex = bis_data.getExt_3();//唯一地址
						Integer bitIndexInteger = Integer.valueOf(bitIndex);
						//已为1 ，没报，则设为0
						String dataValue = retToolInfo.getData_value();
						if(dataValue.equals("1")){
							if(!indexList.contains(bitIndexInteger)){
								retToolInfo.setData_value("0");
							}
						}else {//为0
							if(indexList.contains(bitIndexInteger)){
								retToolInfo.setData_value("1");
							}
						}
						retToolInfo.setData_dsc(bis_data.getExt_5());
						retToolInfo.setEvt_usr(inTrx.getEvt_user());
						retToolInfo.setEvt_timestamp(gEvtTimestamp);
						retToolInfoList.add(retToolInfo);
					}
				}
			}
			retToolInfoDao.saveOrUpdateAll(retToolInfoList);
		}
		return lRc;
	}

	public ArrayList<Integer> testStringIndexOf2(String str){
		String key = "1";
		String reverseStr  = new StringBuffer(str).reverse().toString();
		System.out.println(reverseStr);
		int a = reverseStr.indexOf(key);//*第一个出现的索引位置
		ArrayList<Integer> arrList = new ArrayList<>();
		while (a != -1) {
			System.out.print(a + "\t");
			arrList.add(a);
			a = reverseStr.indexOf(key, a + 1);//*从这个索引往后开始第一个出现的位置
		}
		return arrList;
	}



}
